package com.teacher.service.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.teacher.pojo.entity.AbsentClass;
import com.teacher.pojo.entity.Punishment;
import com.teacher.pojo.enums.PunishmentLevelType;
import com.teacher.pojo.enums.PunishmentLevelType;
import com.teacher.pojo.excel.AbsentClassExcel;
import com.teacher.pojo.excel.PunishmentExcel;
import com.teacher.service.IAbsentClassService;
import com.teacher.service.IPerStudentService;
import com.teacher.service.IPunishmentService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zfm
 * @Date: 2021/7/30 16:17
 */
public class ExcelPunishmentListener extends AnalysisEventListener<PunishmentExcel> {
    private Long termId;
    private IPunishmentService iPunishmentService;

    private List<Punishment> punishmentList = new ArrayList<>();
    private IPerStudentService iPerStudentService;

    public ExcelPunishmentListener(Long termId, IPunishmentService iPunishmentService, IPerStudentService iPerStudentService) {
        this.termId = termId;
        this.iPunishmentService = iPunishmentService;
        this.iPerStudentService = iPerStudentService;
    }

    @Override
    public void invoke(PunishmentExcel punishmentExcel, AnalysisContext analysisContext) {
        if (iPerStudentService.isExit(punishmentExcel.getStudentKey())) {
            Punishment punishment = new Punishment();
            BeanUtils.copyProperties(punishmentExcel, punishment);
            punishment.setTermId(termId);
            if (punishmentExcel.getLevel().equals(PunishmentLevelType.ONE.getType())) {
                punishment.setLevel(PunishmentLevelType.ONE.getCode());
            } else if (punishmentExcel.getLevel().equals(PunishmentLevelType.TWO.getType())) {
                punishment.setLevel(PunishmentLevelType.TWO.getCode());
            } else if (punishmentExcel.getLevel().equals(PunishmentLevelType.THREE.getType())) {
                punishment.setLevel(PunishmentLevelType.THREE.getCode());
            } else if (punishmentExcel.getLevel().equals(PunishmentLevelType.FOUR.getType())) {
                punishment.setLevel(PunishmentLevelType.FOUR.getCode());
            } else {
                punishment.setLevel(PunishmentLevelType.FIVE.getCode());
            }
            punishmentList.add(punishment);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        iPunishmentService.saveBatch(punishmentList);
    }
}
